// 用户认证相关功能
let currentUser = null;
let userToken = localStorage.getItem('userToken');

// 初始化检查用户登录状态
function checkLoginStatus() {
  const token = localStorage.getItem('userToken');
  if (token) {
    authAPI.getUserInfo(token)
      .then(response => {
        if (response.code === 200) {
          currentUser = response.data;
          updateUIForLoggedInUser();
        } else {
          // Token无效，清除本地存储
          localStorage.removeItem('userToken');
          updateUIForGuest();
        }
      })
      .catch(error => {
        console.error('获取用户信息失败:', error);
        localStorage.removeItem('userToken');
        updateUIForGuest();
      });
  } else {
    updateUIForGuest();
  }
}

// 更新UI显示登录用户信息
function updateUIForLoggedInUser() {
  const loginBtn = document.getElementById('loginBtn');
  const registerBtn = document.getElementById('registerBtn');
  const userInfoBtn = document.getElementById('userInfoBtn');
  const logoutBtn = document.getElementById('logoutBtn');
  
  if (loginBtn) loginBtn.style.display = 'none';
  if (registerBtn) registerBtn.style.display = 'none';
  if (userInfoBtn) {
    userInfoBtn.style.display = 'inline-flex';
    userInfoBtn.textContent = currentUser.nickname || '个人中心';
  }
  if (logoutBtn) logoutBtn.style.display = 'inline-flex';
  
  // 更新VIP状态显示
  updateVipStatus();
}

// 更新UI显示游客信息
function updateUIForGuest() {
  const loginBtn = document.getElementById('loginBtn');
  const registerBtn = document.getElementById('registerBtn');
  const userInfoBtn = document.getElementById('userInfoBtn');
  const logoutBtn = document.getElementById('logoutBtn');
  
  if (loginBtn) loginBtn.style.display = 'inline-flex';
  if (registerBtn) registerBtn.style.display = 'inline-flex';
  if (userInfoBtn) userInfoBtn.style.display = 'none';
  if (logoutBtn) logoutBtn.style.display = 'none';
  
  currentUser = null;
}

// 更新VIP状态显示
function updateVipStatus() {
  const vipBadge = document.getElementById('vipBadge');
  if (vipBadge) {
    if (currentUser && currentUser.isVip) {
      vipBadge.style.display = 'inline-flex';
    } else {
      vipBadge.style.display = 'none';
    }
  }
}

// 用户注册
function registerUser(phone, password, verifyCode, nickname) {
  return authAPI.register(phone, password, verifyCode, nickname)
    .then(response => {
      if (response.code === 200) {
        // 注册成功，保存token
        localStorage.setItem('userToken', response.data.token);
        userToken = response.data.token;
        
        // 获取用户信息
        return authAPI.getUserInfo(response.data.token);
      } else {
        throw new Error(response.message || '注册失败');
      }
    })
    .then(response => {
      if (response.code === 200) {
        currentUser = response.data;
        updateUIForLoggedInUser();
        return { success: true, user: currentUser };
      } else {
        throw new Error(response.message || '获取用户信息失败');
      }
    });
}

// 用户登录
function loginUser(phone, password) {
  return authAPI.login(phone, password)
    .then(response => {
      if (response.code === 200) {
        // 登录成功，保存token
        localStorage.setItem('userToken', response.data.token);
        userToken = response.data.token;
        
        // 获取用户信息
        return authAPI.getUserInfo(response.data.token);
      } else {
        throw new Error(response.message || '登录失败');
      }
    })
    .then(response => {
      if (response.code === 200) {
        currentUser = response.data;
        updateUIForLoggedInUser();
        return { success: true, user: currentUser };
      } else {
        throw new Error(response.message || '获取用户信息失败');
      }
    });
}

// 用户登出
function logoutUser() {
  localStorage.removeItem('userToken');
  userToken = null;
  currentUser = null;
  updateUIForGuest();
}

// 更新用户信息
function updateUserInfo(userInfo) {
  if (!userToken) {
    return Promise.reject(new Error('用户未登录'));
  }
  
  return authAPI.updateUserInfo(userToken, userInfo)
    .then(response => {
      if (response.code === 200) {
        // 更新成功，重新获取用户信息
        return authAPI.getUserInfo(userToken);
      } else {
        throw new Error(response.message || '更新用户信息失败');
      }
    })
    .then(response => {
      if (response.code === 200) {
        currentUser = response.data;
        updateUIForLoggedInUser();
        return { success: true, user: currentUser };
      } else {
        throw new Error(response.message || '获取用户信息失败');
      }
    });
}

// 修改密码
function changePassword(oldPassword, newPassword) {
  if (!userToken) {
    return Promise.reject(new Error('用户未登录'));
  }
  
  return authAPI.changePassword(userToken, oldPassword, newPassword)
    .then(response => {
      if (response.code === 200) {
        return { success: true };
      } else {
        throw new Error(response.message || '修改密码失败');
      }
    });
}

// 检查是否需要登录
function checkNeedLogin() {
  if (!currentUser) {
    showLoginModal();
    return true;
  }
  return false;
}

// 检查是否需要支付
function checkNeedPayment(isVipRequired, price) {
  if (isVipRequired && (!currentUser || !currentUser.isVip)) {
    showPaymentModal('vip');
    return true;
  }
  
  if (price > 0) {
    const actualPrice = currentUser ? 0.1 : 1.1;
    showPaymentModal('content', actualPrice);
    return true;
  }
  
  return false;
}

// 显示登录模态框
function showLoginModal() {
  const modal = document.getElementById('loginModal');
  if (modal) {
    modal.style.display = 'block';
  }
}

// 显示支付模态框
function showPaymentModal(type, price) {
  const modal = document.getElementById('paymentModal');
  const paymentTitle = document.getElementById('paymentTitle');
  const paymentAmount = document.getElementById('paymentAmount');
  
  if (modal) {
    if (type === 'vip') {
      paymentTitle.textContent = '开通VIP会员';
      paymentAmount.textContent = '¥9.9';
    } else {
      paymentTitle.textContent = '内容付费';
      paymentAmount.textContent = `¥${price}`;
    }
    
    modal.style.display = 'block';
  }
}

// 关闭模态框
function closeModal(modalId) {
  const modal = document.getElementById(modalId);
  if (modal) {
    modal.style.display = 'none';
  }
}

// 处理支付
function handlePayment(type, productId) {
  if (!userToken) {
    showLoginModal();
    return Promise.reject(new Error('用户未登录'));
  }
  
  let amount = 0;
  let productType = '';
  
  if (type === 'vip') {
    amount = 9.9;
    productType = 'vip';
  } else if (type === 'bazi') {
    amount = currentUser ? 0.1 : 1.1;
    productType = 'bazi_detail';
  } else if (type === 'character') {
    amount = currentUser ? 0.1 : 1.1;
    productType = 'character_detail';
  } else if (type === 'fengshui') {
    amount = currentUser ? 0.1 : 1.1;
    productType = 'fengshui_detail';
  }
  
  // 创建订单
  return paymentAPI.createOrder(userToken, productType, productId, amount)
    .then(response => {
      if (response.code === 200) {
        // 支付订单
        return paymentAPI.payOrder(userToken, response.data.orderNo, 'alipay');
      } else {
        throw new Error(response.message || '创建订单失败');
      }
    })
    .then(response => {
      if (response.code === 200) {
        // 模拟支付成功
        return { success: true, orderNo: response.data.orderNo };
      } else {
        throw new Error(response.message || '支付失败');
      }
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
  // 检查登录状态
  checkLoginStatus();
  
  // 绑定登录按钮事件
  const loginForm = document.getElementById('loginForm');
  if (loginForm) {
    loginForm.addEventListener('submit', function(e) {
      e.preventDefault();
      const phone = document.getElementById('loginPhone').value;
      const password = document.getElementById('loginPassword').value;
      
      loginUser(phone, password)
        .then(() => {
          closeModal('loginModal');
          showToast('登录成功');
        })
        .catch(error => {
          showToast(error.message || '登录失败');
        });
    });
  }
  
  // 绑定注册按钮事件
  const registerForm = document.getElementById('registerForm');
  if (registerForm) {
    registerForm.addEventListener('submit', function(e) {
      e.preventDefault();
      const phone = document.getElementById('registerPhone').value;
      const password = document.getElementById('registerPassword').value;
      const verifyCode = document.getElementById('registerVerifyCode').value;
      const nickname = document.getElementById('registerNickname').value;
      
      registerUser(phone, password, verifyCode, nickname)
        .then(() => {
          closeModal('registerModal');
          showToast('注册成功');
        })
        .catch(error => {
          showToast(error.message || '注册失败');
        });
    });
  }
  
  // 绑定登出按钮事件
  const logoutBtn = document.getElementById('logoutBtn');
  if (logoutBtn) {
    logoutBtn.addEventListener('click', function() {
      logoutUser();
      showToast('已退出登录');
    });
  }
  
  // 绑定支付按钮事件
  const paymentForm = document.getElementById('paymentForm');
  if (paymentForm) {
    paymentForm.addEventListener('submit', function(e) {
      e.preventDefault();
      const paymentType = document.getElementById('paymentType').value;
      const productId = document.getElementById('productId').value;
      
      handlePayment(paymentType, productId)
        .then(() => {
          closeModal('paymentModal');
          showToast('支付成功');
          
          // 如果是VIP支付，更新用户信息
          if (paymentType === 'vip') {
            authAPI.getUserInfo(userToken)
              .then(response => {
                if (response.code === 200) {
                  currentUser = response.data;
                  updateUIForLoggedInUser();
                }
              });
          }
        })
        .catch(error => {
          showToast(error.message || '支付失败');
        });
    });
  }
});

// 显示提示信息
function showToast(message) {
  const toast = document.createElement('div');
  toast.className = 'fixed top-4 right-4 bg-indigo-600 text-white px-4 py-2 rounded shadow-lg z-50';
  toast.textContent = message;
  
  document.body.appendChild(toast);
  
  setTimeout(() => {
    toast.remove();
  }, 3000);
}
